package top.maof.book.utils;

import lombok.extern.slf4j.Slf4j;

import java.net.URL;

@Slf4j
public class URLUtils {
    /**
     * 防止要抓取的网站网站域名变更,
     * 将目标url的域名替换为网站新域名
     */
    public static String changeDomain(String homeUrl, String targetUrl) throws Exception {
        if (homeUrl.startsWith(targetUrl)) {
            return targetUrl;
        } else {
            URL url = new URL(targetUrl);
            String path = url.getPath();
            String query = url.getQuery();
            StringBuilder stringBuilder = new StringBuilder();

            if (homeUrl.endsWith("/")) {
                stringBuilder.append(homeUrl.substring(0, homeUrl.length() - 1));
            } else {
                stringBuilder.append(homeUrl);
            }
            stringBuilder.append(path);
            if (query != null)
                stringBuilder.append("?").append(query);
            return stringBuilder.toString();
        }
    }


    /**
     * 补全从页面中抽取的相对或绝对地址
     */
    public static String completeUrl(String baseUri, String uri) throws Exception {
        return new URL(new URL(baseUri), uri).toString();
     /*   // uri完整
        if (uri.startsWith("http")) return uri;

        // 相对地址
        if (!uri.startsWith("/")) {
            if (baseUri.endsWith("/")) {
                return baseUri + uri;
            } else {
                if (baseUri.startsWith("html") || baseUri.startsWith("htm")) {
                    String substring = baseUri.substring(0, baseUri.lastIndexOf("/") + 1);
                    return substring + uri;
                }
                return baseUri + "/" + uri;

            }

        }
        // 绝对地址
        if (uri.startsWith("/") && !uri.startsWith("//")) {
            String[] pro = baseUri.split("//");
            if (pro[1].contains("/")) {
                String domain = pro[1].split("/")[0];
                return pro[0] + "//" + domain + uri;
            }
            return baseUri + uri;

        }
        // url=//www.ymxxs.com/text_87684.html
        if (uri.startsWith("//")) {
            String[] pro = baseUri.split("//");
            return pro[0] + uri;
        }*/
    }

    public static void main(String[] args) {
        try {
            String url = changeDomain("http://www.aaa.com/", "http://www.lssin.com/shuku_1/xuanhuanxiaoshuo?id=2&d=5");
            log.info(url);
        } catch (Exception e) {

        }

    }
}
